package com.m4f.web.security.filter;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.web.filter.OncePerRequestFilter;

public class ClientSubscriptionFilter extends OncePerRequestFilter {
	
	private static final Logger LOGGER = Logger.getLogger(ClientSubscriptionFilter.class.getName());
	
	
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		LOGGER.info("+++Request: " + request.getRequestURL());
		LOGGER.info("Before-Sessioned client:  " + request.getSession().getAttribute("client"));
		if(request.getSession().getAttribute("client")==null) {
			request.getSession().setAttribute("client", this.extractClient(request));
		}
		LOGGER.info("After-Sessioned client:  " + request.getSession().getAttribute("client"));
		this.doFilter(request, response, filterChain);
	}

	
	/*public void doFilter(javax.servlet.ServletRequest request,
            javax.servlet.ServletResponse response,
            javax.servlet.FilterChain chain)
     throws java.io.IOException,
            javax.servlet.ServletException {
		
		for(ConfigAttribute configAt : super.getSecurityMetadataSource().getAllConfigAttributes()) {
			LOGGER.info("+++++" + configAt + ":" + configAt.getAttribute());
		}
	}*/
	
	private String extractClient(HttpServletRequest request) {
		String client = "";
		String reqURI = request.getRequestURI();
		String[] reqComps = reqURI.split("[/]");
		if(reqURI.startsWith("/")) {
			client = reqComps[1];
		} else {
			client = reqComps[0];
		}
		
		LOGGER.info("+++Request URI: " + client);
		return client;
	}
}